package cc.rboot.flipping.aspect;

import cc.rboot._core.helper.AnnotationHelper;
import cc.rboot._core.helper.MethodHelper;
import cc.rboot.flipping.annotation.Flipping;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

@Aspect
@Component
public class FlippingAspect implements EnvironmentAware {

    private Environment environment;

    @Pointcut("@annotation(cc.rboot.flipping.annotation.Flipping)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Flipping flipping = AnnotationHelper.get(joinPoint, Flipping.class);

        String property = flipping.value();

        Boolean isOn = environment.getProperty(property, Boolean.class);
        if (isOn == null || isOn) {
            return joinPoint.proceed();
        }

        /**
         * 优先执行降级代码
         */
        String degrade = flipping.degrade();
        if (StringUtils.hasText(degrade)) {
            Method method = joinPoint.getThis().getClass().getMethod(degrade, MethodHelper.get(joinPoint).getParameterTypes());
            if (null != method) {
                return method.invoke(joinPoint.getThis(), joinPoint.getArgs());
            }
        }

        //明确特性开关为false时关闭
        throw new Exception("特性开关未打开，暂时无法访问");
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
